
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

#include "pathdelete.h"

PathDelete::PathDelete(QObject *parent) : QObject(parent)
{
    this->init();
}

PathDelete::Status PathDelete::init()
{
    this->settings = new ConfigFile(QCoreApplication::applicationDirPath() + "/" + DEFAULT_FILENAME);

    /* init network env */
    this->deleting = false;
    this->netManager = new QNetworkAccessManager();
    connect(this->netManager,
            &QNetworkAccessManager::finished,
            this,
            &PathDelete::deleteResponse);
    this->baseRequest = new QNetworkRequest();
    baseRequest->setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                                                        "AppleWebKit/537.36 (KHTML, like Gecko) Chrome"
                                                        "/104.0.0.0 Safari/537.36");
    baseRequest->setRawHeader("Host", settings->value(USER_WEB_URL).toString().mid(7).toUtf8());
    baseRequest->setRawHeader("Referer", QString("%1/index.php")
                         .arg(settings->value(USER_WEB_URL).toString()).toUtf8());
    QList<QByteArray> requestHeaderList = baseRequest->rawHeaderList();

    qDebug() << "Print the parameters of the request header:";
    for(int i = 0; i < requestHeaderList.size(); i++) {
        qDebug().noquote() << requestHeaderList.at(i) << ":" << baseRequest->rawHeader(requestHeaderList.at(i));
    }

    return NO_ERROR;
}

PathDelete::~PathDelete()
{
    delete this->settings;
    delete this->netManager;
    delete this->baseRequest;
}

PathDelete::Status PathDelete::startPathDelete(QList<file_t> fileDataList, QString currentNetPath)
{
    qDebug() << "PathDelete::" << __FUNCTION__;
    QString name, phpSessionID;
    name            = this->settings->value(USER_NAME).toString();
    phpSessionID    = this->settings->value(USER_PHPSESSID).toString();
    if(name.length() == 0) { return INVALID_NAME; }
    if(phpSessionID.length() == 0) { return INVALID_PHPSESSID; }

    this->baseRequest->setRawHeader("Cookie", QString("PHPSESSID=%1; secros_user_language=zh_CN; secros_name=%2")
            .arg(phpSessionID)
            .arg(name)
            .toUtf8());
    if(fileDataList.size() == 0) { return INVALID_FILE_DATA_LIST; }

    /* Start concatenating strings. */
    /* Sample : list=[{"type":"file","path":"%252Ftest2aaa.txt"},{...}]" */
    QString postBodyStr = "list=[";
    for(int i = 0; i < fileDataList.size(); i++) {
        file_t fileData = fileDataList.at(i);
        QString filepath = "";
        if(currentNetPath.length() == 0) {
            filepath = QString("%1%2")
                    .arg(fileData.path.length() == 0 ? QString("/") : fileData.path)
                    .arg(fileData.name);
        } else {
            filepath = QString("%1%2")
                    .arg(currentNetPath)
                    .arg(fileData.name);
        }
        QString jsonStr = QString("{\"type\":\"%1\",\"path\":\"%2\"}%3")
                .arg(fileData.type)
                .arg(filepath)
                .arg(fileDataList.size() - 1 == i ? "" : ",");
        postBodyStr += jsonStr;
    }
    postBodyStr += "]";
    qDebug().noquote() << QString("PathDelete::%1 postBodyStr:%2")
                          .arg(__FUNCTION__, postBodyStr);

    this->deleting = true;
    QString url;
    QNetworkRequest req = *(this->baseRequest);
    url += settings->value(USER_WEB_URL).toString();
    url += QString("/index.php?explorer/pathDelete");
    req.setUrl(QUrl(url));
    qDebug("Start request '%s' .\n", url.toLatin1().data());

    QList<QByteArray> requestHeaderList = req.rawHeaderList();
    qDebug() << "Print the parameters of the request header:";
    for(int i = 0; i < requestHeaderList.size(); i++) {
        qDebug().noquote() << requestHeaderList.at(i) << ":" << req.rawHeader(requestHeaderList.at(i));
    }

    this->netManager->post(req, postBodyStr.toUtf8());

    return NO_ERROR;
}

void PathDelete::deleteResponse(QNetworkReply *reply)
{
    qDebug() << __FUNCTION__;
    this->deleting = false;
    /* 过滤请求错误 */
    if(reply->error() != QNetworkReply::NoError) {
        emit finished(RESPONSE_ERROR, reply->errorString());
        return ;
    }

    /* 判断响应数据 */
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    /* 如果解析响应状态码错误或者状态码!=200 */
    qDebug("%s Response statusCode:%d", __FUNCTION__, statusCode.toInt());
    if(!statusCode.isValid() || statusCode.toInt() != 200) {
        QVariant reason =  reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
        if(reason.isValid())
            emit finished(RESPONSE_ERROR, reason.toString());
        else
            emit finished(RESPONSE_ERROR, QString("%1 Unknown response error").arg(__FUNCTION__));
        return ;
    }

    // print response data
    QByteArray jsonByteArray = reply->readAll();
    QJsonParseError jsonParseError;
    QJsonObject replyJsonObj = QJsonDocument::fromJson(jsonByteArray, &jsonParseError).object();
    if(jsonParseError.error != QJsonParseError::NoError) {
        qDebug() << "Response Data:";
        qDebug().noquote() << jsonByteArray;
        qDebug() << "Upload::" << __FUNCTION__ << "json parse error:" << jsonParseError.errorString();
        emit finished(JSON_ERROR, "Json parse error:" + jsonParseError.errorString());
        return ;
    }
    qDebug().noquote() << "Json Parse Done Data:\n" <<
                          QJsonDocument::fromJson(jsonByteArray, &jsonParseError)
                          .toJson(QJsonDocument::Indented);

    bool code = replyJsonObj.value("code").toBool();
    double user_time = replyJsonObj.value("user_time").toDouble();
    QString data = replyJsonObj.value("data").toString();
    QString info = replyJsonObj.value("info").toString();
    emit finished(code?NO_ERROR:RESPONSE_ERROR,
                  QString("user_time:%1\ndata:%2\ninfo:%3")
                      .arg(user_time).arg(data).arg(info));
}

bool PathDelete::isDeleting()
{
    return this->deleting;
}















